<template>
  <Transition name="fade">
    <div v-if="showDialog" class="dialog-overlay">
      <div class="dialog">
        <h2 class="dialog-title">修改知识信息</h2>
        <form @submit.prevent="handleSubmit">
          <div class="form-item">
            <label for="knowledge_id">知识 ID:</label>
            <input v-model="formData.knowledgeId" type="text" id="knowledge_id" readonly />
          </div>
          <div class="form-item">
            <label for="title">标题:</label>
            <input v-model="formData.title" type="text" id="title" required />
          </div>
          <div class="form-item">
            <label for="content">内容:</label>
            <input v-model="formData.content" type="text" id="content" required />
          </div>
          <div class="form-item">
            <label for="publishTime">发布时间:</label>
            <input v-model="formData.publishTime" type="datetime-local" id="publishTime" required />
          </div>
          <div class="form-item">
            <label for="image">图片:</label>
            <input type="file" @change="handleFileUpload" id="image" />
            <div v-if="imageUrl">
              <span>{{ imageName }}</span>
            </div>
          </div>
          <div class="form-item">
            <label for="consultantId">顾问 ID:</label>
            <input v-model="formData.consultantId" type="text" id="consultantId" required />
          </div>
          <div class="button-container">
            <button type="submit" class="button">确定</button>
            <button @click="showDialog = false" class="button">取消</button>
          </div>
        </form>
      </div>
    </div>
  </Transition>
</template>

<script setup>
import { ref } from 'vue';
import { Transition } from 'vue';
import axios from 'axios';


// 控制对话框的显示状态
const showDialog = ref(true);
// 存储表单数据
const formData = ref({
  knowledgeId: '',
  title: '',
  content: '',
  publishTime: '',
  image: null,
  consultantId: 0
});
// 存储上传的图片的 URL
const imageUrl = ref(null);
// 存储图片名称
const imageName = ref('');


// 定义要发出的事件
const emit = defineEmits(['updateKnowledge']);


// 处理文件上传
const handleFileUpload = (event) => {
  const file = event.target.files[0];
  if (!file) {
    alert('请选择文件！');
    return;
  }

  // 创建 FormData 对象并添加文件
  const uploadFormData = new FormData();
  uploadFormData.append('file', file);

  // 调用文件上传接口
  axios
      .post('http://127.0.0.1:9090/file/uploadsn', uploadFormData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      })
      .then((response) => {
        console.log('文件上传成功：', response.data);

        // 验证返回数据结构
        const additionalData = response?.data?.additionalData;
        const fileNames = additionalData?.fileNames[0];

        if (fileNames) {
          formData.value.image = fileNames; // 使用上传的第一个文件名
          imageName.value = fileNames; // 显示上传成功的文件名
        } else {
          alert('上传失败，未获取到文件名！');
        }
      })
      .catch((error) => {
        console.error('文件上传失败：', error);
        alert('文件上传失败，请重试！');
      });
};


// 处理表单提交
const handleSubmit = async () => {
  try {
    const response = await axios.put('http://127.0.0.1:9090/psychologicalKnowledge', JSON.stringify(formData.value), {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    console.log(response.data);
    emit('updateKnowledge', formData.value);
    showDialog.value = false;
  } catch (error) {
    console.error('调用接口修改知识时出错:', error);
    alert('修改知识失败，请重试！');
  }
};


// 接收传递过来的知识数据，初始化表单数据
const props = defineProps({
  knowledge: {
    type: Object,
    required: true
  }
});


// 初始化表单数据
const initFormData = () => {
  formData.value = {...props.knowledge};
};


initFormData();


</script>


<style scoped>
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}
.dialog {
  background-color: white;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
  width: 500px;
  height: 470px;
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
}
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter,
.fade-leave-to {
  opacity: 0;
}
.form-item {
  display: flex;
  flex-direction: column;
}
.form-item input {
  height: 30px;
  font-size: 16px;
}
.button-container {
  display: flex;
  justify-content: space-evenly;
}
.button {
  height: 25px;
  font-size: 14px;
  background-color: rgba(64, 158, 255, 0.81);
  width: 100px;
  text-align: center;
  cursor: pointer;
  border-radius: 10px;
  color: white;
  border: none;
}
.dialog-title {
  font-size: 20px;
  margin: 0;
  text-align: center;
}
</style>